<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>管理员页</title>
    <link rel="stylesheet" href="/static/manager.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.ckeditor.com/ckeditor5/35.3.2/classic/ckeditor.js"></script>
</head>
<body>
<h1 class="admin-welcome">欢迎来到管理员界面</h1>
<div class="button-container">
    <button id="usermanageButton">管理用户</button>
    <button id="logoutButton">退出登录</button>
</div>
<div class="container">
    <div class="header-bar">
        <h1 style="margin:0; color: var(--primary-color);">管理博文</h1>
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput" placeholder="搜索博文...">
            <i class="fas fa-search search-icon"></i>
        </div>
    </div>

    <div class="card-grid" id="postContainer">
        <!-- 动态卡片内容 -->
    </div>
</div>
<script>
    $(document).ready(function() {
        const role = localStorage.getItem('role');
        if (role !== '1') { // 非管理员
            alert('无权访问此页面');
            window.location.href = '/login';
        }
        // 添加退出登录按钮的点击事件
        $('#logoutButton').click(function() {
            localStorage.removeItem('token'); // 移除 token
            localStorage.removeItem('uid');
            localStorage.removeItem('role');
            alert("已退出登录");
            window.location.href = '/login'; // 跳转回登录页
        });
        //添加管理用户按钮的点击事件
        $('#usermanageButton').click(function() {
            window.location.href = '/usermanageHTML';
        });

    });

    $(document).ready(function () {
        const token = localStorage.getItem('token');
        let allPosts = [];

        // 修改后的卡片模板
        function createPostCard(post) {
            return `
            <div class="card" data-pid="${post.pid}">
                ${post.imageurl ? `
                <div class="card-image" style="background-image: url('${post.imageurl}')">
                    <div class="image-overlay"></div>
                </div>` : ''}
                <div class="card-content">
                    <h3 class="card-title">${post.title}</h3>
                    <p class="card-brief">${post.brief}</p>
                </div>
                <div class="card-actions">
                    <button class="action-btn view-btn" title="查看" data-pid="${post.pid}">
                        <i class="fas fa-external-link-alt"></i>
                    </button>
                    <button class="action-btn edit-btn" title="编辑" data-pid="${post.pid}">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="action-btn delete-btn" title="删除" data-pid="${post.pid}">
                        <i class="fas fa-trash"></i>
                    </button>
                    <button class="action-btn sort-btn" title="分类" data-pid="${post.pid}">
                        <i class="fas fa-tag"></i>
                    </button>
                </div>
            </div>
        `;
        }

        // 新增事件委托处理
        $(document).on('click', '.view-btn', function() {
            const pid = $(this).data('pid');
            window.location.href = `/api/v1/post/searchpidHTML?id=${pid}`;
        });

        $(document).on('click', '.edit-btn', function() {
            const pid = $(this).data('pid');
            const post = allPosts.find(p => p.pid === pid);
            if (post) createUpdateHandler(post)();
        });

        $(document).on('click', '.delete-btn', function() {
            const pid = $(this).data('pid');
            const post = allPosts.find(p => p.pid === pid);
            if (post) createDeleteHandler(post)();
        });

        $(document).on('click', '.sort-btn', function() {
            const pid = $(this).data('pid');
            const post = allPosts.find(p => p.pid === pid);
            if (post) createSortHandler(post)();
        });

        // 渲染卡片
        function renderPosts(posts) {
            const container = $('#postContainer');
            const validPosts = Array.isArray(posts) ? posts : [];

            if (validPosts.length === 0) {
                container.html(`
            <div class="empty-state">
                <i class="fas fa-file-alt fa-3x"></i>
                <h3>暂无博文</h3>
                <p>点击右上角按钮创建你的第一篇博文</p>
            </div>
        `);
                return;
            }

            container.html(validPosts.map(post => createPostCard(post)).join(''));
        }

        // 初始化加载数据
        function loadPosts() {
            // 先显示加载状态
            renderPosts([]);

            fetch('/api/v1/post', {
                headers: {
                    'Token': token,
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);
                    return response.json();
                })
                .then(data => {
                    if (data.code === 0) {
                        allPosts = data.data || [];
                    } else {
                        allPosts = [];
                        console.warn('接口返回错误:', data.msg);
                    }
                    renderPosts(allPosts);
                })
                .catch(error => {
                    console.error('请求失败:', error);
                    allPosts = [];
                    renderPosts(allPosts);
                    Swal.fire('错误', '数据加载失败，请刷新重试', 'error');
                });
        }

        // 搜索功能
        $('#searchInput').on('input', function() {
            const term = $(this).val().toLowerCase();
            const filtered = allPosts.filter(post =>
                post.title.toLowerCase().includes(term) ||
                post.brief.toLowerCase().includes(term)
            );
            renderPosts(filtered);
        });

        // 以下为删除和修改逻辑
        function createDeleteHandler(post) {
            return async function () {
                const { isConfirmed } = await Swal.fire({
                    title: '确认删除？',
                    text: "删除后将无法恢复！",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: '确认删除'
                });

                if (isConfirmed) {
                    try {
                        const response = await fetch(`/api/v1/post/${post.pid}`, {
                            method: 'DELETE',
                            headers: { 'Content-Type': 'application/json' }
                        });

                        if (response.ok) {
                            // 更新本地数据并重新渲染
                            allPosts = allPosts.filter(p => p.pid !== post.pid);
                            renderPosts(allPosts);
                            Swal.fire('成功', '帖子已删除', 'success');
                        } else {
                            throw new Error('删除失败');
                        }
                    } catch (error) {
                        Swal.fire('错误', error.message, 'error');
                    }
                }
            };
        }

        function createUpdateHandler(post) {
            return async function () {
                const originalData = {
                    title: post.title,
                    brief: post.brief,
                    content: post.content,
                    imageurl: post.imageurl
                };

                const formHTML = `
<div class="vertical-form">
    <div class="form-item">
        <label>标题</label>
        <input type="text" id="updatePostTitle" value="${originalData.title}" required placeholder="请输入标题">
    </div>
    <div class="form-item">
        <label>简介</label>
        <textarea id="updatePostBrief" placeholder="请输入简介" style="
            resize: none;
            height: 100px;
            width: 725px;
            overflow-y: auto;
            white-space: pre-wrap;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        " >${originalData.brief}</textarea>
    </div>
    <div class="form-item">
        <label>内容</label>
        <div id="updatePostEditor"></div> <!-- 修改为div容器 -->
    </div>
    <div class="form-item">
        <label>图片URL</label>
        <input type="url" id="updatePostImageUrl" value="${originalData.imageurl}" placeholder="请输入图片URL">
    </div>
</div>
`;

                let updateEditor; // 在外部定义编辑器变量

                const { value: formValues } = await Swal.fire({
                    title: '编辑帖子',
                    html: formHTML,
                    width: '800px', // 增加弹窗宽度
                    showCancelButton: true,
                    confirmButtonText: '提交修改',
                    willOpen: () => {
                        // 初始化编辑器
                        ClassicEditor.create(document.querySelector('#updatePostEditor'), {
                            toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote']
                        }).then(newEditor => {
                            updateEditor = newEditor;
                            updateEditor.setData(originalData.content); // 填充原始内容
                        }).catch(error => {
                            console.error('编辑器初始化失败:', error);
                        });
                    },
                    preConfirm: () => {
                        return new Promise((resolve) => {
                            if (updateEditor) {
                                resolve({
                                    title: document.getElementById('updatePostTitle').value.trim(),
                                    brief: document.getElementById('updatePostBrief').value.trim(),
                                    content: updateEditor.getData(), // 获取富文本内容
                                    imageurl: document.getElementById('updatePostImageUrl').value.trim()
                                });
                            } else {
                                Swal.showValidationMessage('编辑器初始化未完成');
                                resolve(false);
                            }
                        });
                    },
                    didClose: () => {
                        // 销毁编辑器实例
                        if (updateEditor) {
                            updateEditor.destroy().catch(error => {
                                console.error('编辑器销毁失败:', error);
                            });
                        }
                    }
                });

                if (!formValues) return;

                const mergedData = {
                    title: formValues.title.trim() === '' ? originalData.title : formValues.title,
                    brief: formValues.brief.trim() === '' ? originalData.brief : formValues.brief,
                    content: formValues.content.trim() === '' ? originalData.content : formValues.content,
                    imageurl: formValues.imageurl.trim() === '' ? originalData.imageurl : formValues.imageurl,
                    pid: post.pid,
                    uid: post.uid,
                    likecount: post.likecount,
                    collectcount: post.collectcount
                };

                try {
                    const response = await fetch(`/api/v1/post/${post.pid}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(mergedData)
                    });

                    if (response.ok) {
                        location.reload();
                    } else {
                        const error = await response.json();
                        Swal.fire('修改失败', error.message || '服务器错误', 'error');
                    }
                } catch (error) {
                    Swal.fire('网络错误', '请检查网络连接后重试', 'error');
                    console.error('更新请求失败:', error);
                }
            };
        }

        function createSortHandler(post){
            return async function() {
                // 分类选项数据（可以从后端动态获取）
                const typeOptions = [
                    {id: 1, name: '小白必看'},
                    {id: 2, name: '前沿突破'},
                    {id: 3, name: '实际应用'},
                    {id: 4, name: '行业新闻'},
                    {id: 5, name: '技术文章'},
                    {id: 6, name: '电商方向'},
                    {id: 7, name: '工业方向'},
                    {id: 8, name: '金融方向'},
                    {id: 9, name: '医疗方向'},
                    {id: 10, name: '生活随笔'}
                ];

                // 构建分类选择表单
                const formHTML = `
<div class="type-form">
    ${typeOptions.map(type => `
    <label class="type-item">
        <input type="checkbox" name="postType" value="${type.id}">
        ${type.name}
    </label>
    `).join('')}
</div>
<style>
.type-form {
    display: grid;
    gap: 12px;
    padding: 10px;
}
.type-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px;
    border: 1px solid #eee;
    border-radius: 4px;
}
</style>
`;

                const { value: formValues } = await Swal.fire({
                    title: '选择文章分类',
                    html: formHTML,
                    showCancelButton: true,
                    confirmButtonText: '提交分类',
                    preConfirm: () => {
                        const selected = [];
                        document.querySelectorAll('input[name="postType"]:checked').forEach(checkbox => {
                            selected.push(parseInt(checkbox.value));
                            //测试是否选择类型成功
                            console.log("已选择类型序号为",parseInt(checkbox.value));
                        });
                        return selected;
                    }
                });

                if (formValues && formValues.length > 0) {
                    try {
                        const response = await fetch(`/type/post/${post.pid}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Token': localStorage.getItem('token')
                            },
                            body: JSON.stringify({
                                ip: formValues // 发送选中的分类ID数组
                            })
                        });

                        const result = await response.json();
                        if (result.code === 0) {
                            Swal.fire('成功', '分类设置成功', 'success');
                        } else {
                            Swal.fire('错误', result.msg || '操作失败', 'error');
                        }
                    } catch (error) {
                        Swal.fire('错误', '请求发送失败', 'error');
                    }
                }
            };
        }
        loadPosts();
    });
</script>
</body>
</html>